package pattern.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * 懒汉式单例
 */
public class LazyMan {
    private static boolean jdg = false;

    private LazyMan() {
        synchronized (LazyMan.class){
            if (jdg == false){
                jdg = true;
            }
            else{
                throw new RuntimeException("不要破坏单例");
            }
        }
    }

    private static LazyMan lazyMan;

    public static LazyMan getInstance() {
        if (lazyMan == null) {
            synchronized (LazyMan.class) {
                if (lazyMan == null) {
                    lazyMan = new LazyMan();
                    jdg = true;
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws Exception {
//        LazyMan lazyMan3 = new LazyMan();

        Class<LazyMan> lazyManClass = LazyMan.class;
        Field jdg = lazyManClass.getDeclaredField("jdg");
        jdg.setAccessible(true);
        
        Constructor<LazyMan> lazyManConstructor = lazyManClass.getDeclaredConstructor();
        lazyManConstructor.setAccessible(true);
        LazyMan lazyMan1 = lazyManConstructor.newInstance();
        
        jdg.set(lazyMan1,false);
        LazyMan lazyMan2 = lazyManConstructor.newInstance();

        System.out.println(lazyMan1);
        System.out.println(lazyMan2);
        
    }
}
